package guowei.guliproduct.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import guowei.common.utils.PageUtils;
import guowei.common.utils.Query;
import guowei.guliproduct.product.dao.CategoryBrandRelationDao;
import guowei.guliproduct.product.dao.CategoryDao;
import guowei.guliproduct.product.entity.CategoryEntity;
import guowei.guliproduct.product.service.CategoryService;
import guowei.guliproduct.product.vo.CateLogErSan;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Autowired
    protected StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(new Query<CategoryEntity>().getPage(params), new QueryWrapper<CategoryEntity>());

        return new PageUtils(page);
    }

    /**
     * 得到所有分类，然后按照一级分类包含二级分类和三级分类（递归方法） 定义一个新属性 子分类list集合
     *
     * @return
     */
    @Override
    public List<CategoryEntity> getAlllists() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

//找到所有一级分类即ParentCid=0的分类  利用Stream流的filter()方法。    map()方法则是为我们的childrens属性赋值   sorted()方法为我们根据sort属性排序
        List<CategoryEntity> ParentsList = categoryEntities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
//为所有一级二级菜单附上值
        }).map((parentMenu) -> {
            parentMenu.setChildrens(setChildrenss(parentMenu, categoryEntities));
            return parentMenu;
        }).sorted((parentMenu1, parentMenu2) -> {
            return (parentMenu1.getSort() == null ? 0 : parentMenu1.getSort()) - (parentMenu2.getSort() == null ? 0 : parentMenu2.getSort());
        }).collect(Collectors.toList());
        return ParentsList;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //Todo 检查菜单是否可以删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public void deleteOneByCatId(Long catId) {
        baseMapper.deleteById(catId);
    }

    /**
     * 递归求出子属性及其父属性的路径信息
     * [255,25,2]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findParentPath(Long catelogId) {
        ArrayList<Long> path = new ArrayList<>();
        Long[] digui = digui(catelogId, path);
        return digui;
    }

    @Override
    @Transactional
    @CacheEvict(value = {"category"},allEntries = true)
    public void updateDetails(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationDao.updateByCatelogIdAndCatelogName(category.getCatId(), category.getName());
    }

    /**
     * 得到所有一级分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> selectAllOnes() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid", 0);
        List<CategoryEntity> list = this.list(wrapper);
        return list;
    }


    private Long[] digui(Long categoryId, ArrayList<Long> path) {
        path.add(categoryId);
        if (this.getById(categoryId).getParentCid() != 0) {
            digui(this.getById(categoryId).getParentCid(), path);
        }
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }


    /**
     * 递归方法，实现一级分类和二级分类都有其子分类
     *
     * @param category
     * @param allCaterories
     * @return
     */
    public List<CategoryEntity> setChildrenss(CategoryEntity category, List<CategoryEntity> allCaterories) {
//        得到一级菜单，过滤得到该一级菜单的所有二级菜单
        List<CategoryEntity> childrensList = allCaterories.stream().filter((category1) -> {
            return category1.getParentCid() == category.getCatId();
//         该一级菜单的所有二级菜单 递归实现 得到所有三级菜单
        }).map((category2) -> {
            category2.setChildrens(setChildrenss(category2, allCaterories));
            return category2;
        }).sorted((parentMenu1, parentMenu2) -> {
            return (parentMenu1.getSort() == null ? 0 : parentMenu1.getSort()) - (parentMenu2.getSort() == null ? 0 : parentMenu2.getSort());
        }).collect(Collectors.toList());
        return childrensList;
    }

    /**
     * 利用SpringCache技术得到最终的方法
     *      sync = true作用加了一个本地锁，  查询时调用的是 (synchronized)加锁的get方法
     * @return
     */
    @Cacheable(value = {"category"},key = "#root.methodName",sync = true)
    @Override
    public Map<String, List<CateLogErSan>> getYiErSan() {

        List<CategoryEntity> alllist = this.list(null);

        List<CategoryEntity> catelog1list = this.getlisybypid(alllist, 0L);
        Map<String, List<CateLogErSan>> map = catelog1list.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

            List<CategoryEntity> catelog2list = this.getlisybypid(alllist, v.getCatId());

            List<CateLogErSan> c2list = catelog2list.stream().map(c2 -> {
                CateLogErSan ersan = new CateLogErSan(v.getCatId().toString(), null, c2.getCatId().toString(), c2.getName());

                List<CategoryEntity> catelog3list = this.getlisybypid(alllist, c2.getCatId());
                List<CateLogErSan.Catelog3Vo> c3list = catelog3list.stream().map(c3 -> {
                    CateLogErSan.Catelog3Vo catelog3Vo = new CateLogErSan.Catelog3Vo(c2.getCatId().toString(), c3.getCatId().toString(), c3.getName());
                    return catelog3Vo;
                }).collect(Collectors.toList());
                ersan.setCatalog3List(c3list);
                return ersan;
            }).collect(Collectors.toList());
            return c2list;
        }));
        return map;
    }


    /**
     * 获取所有一级分类 并传入cache
     * @return
     */
    @Cacheable(value = {"category"},key = "#root.methodName")
    @Override
    public List<CategoryEntity> getyi() {
        System.out.println("访问了数据库");
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid", 0);
        List<CategoryEntity> list = this.list(wrapper);
        return list;
    }


    /**
     * 利用redis缓存技术得到数据 过时了
     * 1、空结果缓存:解决缓存穿透
     * 2、设置过期时间(加随机值)。解决缓存雪崩
     * 3、加锁:解决缓存击穿
     */
    public Map<String, List<CateLogErSan>> getYiErSanOld() {
        String yiersan = stringRedisTemplate.opsForValue().get("yiersan");
        if (StringUtils.isEmpty(yiersan)) {
            System.out.println("缓存未命中，将要查询数据库");
            Map<String, List<CateLogErSan>> map = this.getYiErSanDBByRedissonSuo();
            String s = JSON.toJSONString(map);
            stringRedisTemplate.opsForValue().set("yiersan", s, 1, TimeUnit.DAYS);
            return map;
        } else {
            System.out.println("缓存命中，直接返回数据");
            Map<String, List<CateLogErSan>> map = JSON.parseObject(yiersan, new TypeReference<Map<String, List<CateLogErSan>>>() {
            });
            return map;
        }
    }
    /**
     * 得到所有二级三级分类信息 利用RedissonClient操作分布式锁 自动
     *
     * @return
     */
    public Map<String, List<CateLogErSan>> getYiErSanDBByRedissonSuo() {
        //占用分布式锁  自动阻塞lock以下的代码 直到解锁
        RLock lock = redissonClient.getLock("yiersan");
        lock.lock();
        Map<String, List<CateLogErSan>> stringListMap;
            try {
                stringListMap = getStringListMap();
            }finally {
                lock.unlock();
            }
            return stringListMap;
    }

    /**
     * 得到所有二级三级分类信息 利用分布式锁 手动
     *
     * @return
     */
    public Map<String, List<CateLogErSan>> getYiErSanDBByRedisSuo() {
        //占用分布式锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            Map<String, List<CateLogErSan>> stringListMap;
            try {
                stringListMap = getStringListMap();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),Arrays.asList("lock"),uuid);
            }
            return stringListMap;
        }else {
            System.out.println("获取分布式锁失败");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return getYiErSanDBByRedisSuo();
        }
    }

    private Map<String, List<CateLogErSan>> getStringListMap() {
        String yiersan = stringRedisTemplate.opsForValue().get("yiersan");
        if (StringUtils.isEmpty(yiersan)) {
            System.out.println("查询了sjk，并得到了数据");
            List<CategoryEntity> alllist = this.list(null);

            List<CategoryEntity> catelog1list = this.getlisybypid(alllist, 0L);
            Map<String, List<CateLogErSan>> map = catelog1list.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                List<CategoryEntity> catelog2list = this.getlisybypid(alllist, v.getCatId());

                List<CateLogErSan> c2list = catelog2list.stream().map(c2 -> {
                    CateLogErSan ersan = new CateLogErSan(v.getCatId().toString(), null, c2.getCatId().toString(), c2.getName());

                    List<CategoryEntity> catelog3list = this.getlisybypid(alllist, c2.getCatId());
                    List<CateLogErSan.Catelog3Vo> c3list = catelog3list.stream().map(c3 -> {
                        CateLogErSan.Catelog3Vo catelog3Vo = new CateLogErSan.Catelog3Vo(c2.getCatId().toString(), c3.getCatId().toString(), c3.getName());
                        return catelog3Vo;
                    }).collect(Collectors.toList());
                    ersan.setCatalog3List(c3list);
                    return ersan;
                }).collect(Collectors.toList());
                return c2list;
            }));
            String s = JSON.toJSONString(map);
            stringRedisTemplate.opsForValue().set("yiersan", s, 1, TimeUnit.DAYS);
            return map;
        } else {
            System.out.println("进入了查询方法，但得到了缓存，不查询数据库");
            Map<String, List<CateLogErSan>> map = JSON.parseObject(yiersan, new TypeReference<Map<String, List<CateLogErSan>>>() {
            });
            return map;
        }
    }

    /**
     * 得到所有二级三级分类信息 利用synchronized(this)只是本地锁，不适合分布式锁
     *
     * @return
     */
    public Map<String, List<CateLogErSan>> getYiErSanDB() {
//业务优化
        synchronized (this) {
            String yiersan = stringRedisTemplate.opsForValue().get("yiersan");
            if (StringUtils.isEmpty(yiersan)) {
                System.out.println("查询了sjk，并得到了数据");
                List<CategoryEntity> alllist = this.list(null);

                List<CategoryEntity> catelog1list = this.getlisybypid(alllist, 0L);
                Map<String, List<CateLogErSan>> map = catelog1list.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                    List<CategoryEntity> catelog2list = this.getlisybypid(alllist, v.getCatId());

                    List<CateLogErSan> c2list = catelog2list.stream().map(c2 -> {
                        CateLogErSan ersan = new CateLogErSan(v.getCatId().toString(), null, c2.getCatId().toString(), c2.getName());

                        List<CategoryEntity> catelog3list = this.getlisybypid(alllist, c2.getCatId());
                        List<CateLogErSan.Catelog3Vo> c3list = catelog3list.stream().map(c3 -> {
                            CateLogErSan.Catelog3Vo catelog3Vo = new CateLogErSan.Catelog3Vo(c2.getCatId().toString(), c3.getCatId().toString(), c3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        ersan.setCatalog3List(c3list);
                        return ersan;
                    }).collect(Collectors.toList());
                    return c2list;
                }));
                String s = JSON.toJSONString(map);
                stringRedisTemplate.opsForValue().set("yiersan", s, 1, TimeUnit.DAYS);
                return map;
            } else {
                System.out.println("进入了查询方法，但得到了缓存");
                Map<String, List<CateLogErSan>> map = JSON.parseObject(yiersan, new TypeReference<Map<String, List<CateLogErSan>>>() {
                });
                return map;
            }
        }
    }


    /**
     * 避免查询数据库，而是从list集合里面查询 性能优化，访问数据库所需的时间远远大于访问list集合
     *
     * @param alllist
     * @param parentCid
     * @return
     */
    public List<CategoryEntity> getlisybypid(List<CategoryEntity> alllist, Long parentCid) {
        List<CategoryEntity> collect = alllist.stream().filter(item -> {
            return item.getParentCid() == parentCid;
        }).collect(Collectors.toList());
        return collect;
    }


}